from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from sse_starlette.sse import EventSourceResponse
from business.ollama.chat_doc import OllamaChatDoc
from business.ollama.chat_chat import OllamaChatBase
from business.apply.llm_check import LLMCheck, Rule, FormData
from pydantic import BaseModel
import uuid

class ChatRequest(BaseModel):
    query: str
    session_id: str = None  # 可选的会话ID

app = FastAPI()

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 在生产环境中应该设置具体的域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 初始化OllamaChat实例（带知识库）
chat_doc_instance = OllamaChatDoc()

# 初始化OllamaChat实例（不带知识库，HTTP服务模式下禁用verbose）
chat_instance = OllamaChatBase(verbose=False)

# 初始化LLMCheck实例
llm_check_instance = LLMCheck()

@app.get("/")
async def root():
    return {"message": "Welcome to the JhmAi API"}

@app.post("/chat_doc")
async def chat_doc_endpoint(request: Request, chat_request: ChatRequest):
    """
    聊天端点，查询知识库的，返回SSE流
    """
    # 如果没有提供session_id，生成一个新的
    session_id = chat_request.session_id or str(uuid.uuid4())
    return EventSourceResponse(chat_doc_instance.stream_chat(chat_request.query, session_id))

@app.post("/chat")
async def chat_endpoint(request: Request, chat_request: ChatRequest):
    """
    聊天端点，聊天加代理，返回SSE流
    """
    # 如果没有提供session_id，生成一个新的
    session_id = chat_request.session_id or str(uuid.uuid4())
    return EventSourceResponse(chat_instance.stream_chat(chat_request.query, session_id))

@app.post("/clear_session/{session_id}")
async def clear_session_endpoint(session_id: str):
    """
    清除指定会话的历史记录
    """
    chat_doc_instance.clear_session(session_id)
    return {"status": "success", "message": "Session cleared successfully"}

@app.post("/check_rules")
async def check_rules_endpoint(rules: Rule, form_data: FormData):
    """
    检查表单是否符合规则的端点
    """
    result = llm_check_instance.check_rules(rules, form_data)
    return result

@app.get("/health")
async def health_check():
    """
    健康检查端点
    """
    return {"status": "healthy"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=6005)
